package edu.sju.chenshu.common.core.domain;

import edu.sju.chenshu.common.core.enums.ResultCode;
import lombok.Getter;
import lombok.Setter;

//统一响应数据
@Getter
@Setter
public class Result<T> {
    private int code;
    private String msg;
    private T data;

    //操作成功：1000
    public static <T> Result<T> ok() {
        return assembleResult(null, ResultCode.SUCCESS);
    }

    //操作成功：1000（带data）
    public static <T> Result<T> ok(T data) {
        return assembleResult(data, ResultCode.SUCCESS);
    }

    //操作失败：3000
    public static <T> Result<T> fail() {
        return assembleResult(null, ResultCode.FAILED);
    }

    //操作失败：自定义失败码+失败信息
    public static <T> Result<T> fail(int code, String msg) {
        return assembleResult(code, msg, null);
    }

    //操作失败：指定ResultCode
    public static <T> Result<T> fail(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    private static <T> Result<T> assembleResult(T data, ResultCode resultCode) {
        Result<T> result = new Result<>();
        result.setCode(resultCode.getCode());
        result.setData(data);
        result.setMsg(resultCode.getMsg());
        return result;
    }

    //用于自定义ResultCode以外的响应数据
    private static <T> Result<T> assembleResult(int code, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }
}
